package com.example.imagepicker;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

import com.lcw.library.imagepicker.ImagePicker;
import com.lcw.library.imagepicker.data.MediaFile;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE_CHOOSE = 236;
    // 权限处理已移至相册库中，不再需要权限请求码

    private Button btnSelectImage;
    private Button btnSelectVideo;
    private Button btnSelectMixed;
    private Button btnSelectSingle;
    private Switch switchCamera;
    private Switch switchPermissionDialog;
    private RecyclerView recyclerView;
    private SelectedImageAdapter adapter;
    private List<MediaFile> selectedImages = new ArrayList<>();
    
    // 配置选项
    private boolean showCameraButton = false;  // 默认不显示拍照按钮
    private boolean showPermissionDialog = true;  // 默认显示权限说明弹窗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        initRecyclerView();
        initListeners();
    }

    private void initViews() {
        btnSelectImage = findViewById(R.id.btn_select_image);
        btnSelectVideo = findViewById(R.id.btn_select_video);
        btnSelectMixed = findViewById(R.id.btn_select_mixed);
        btnSelectSingle = findViewById(R.id.btn_select_single);
        switchCamera = findViewById(R.id.switch_camera);
        switchPermissionDialog = findViewById(R.id.switch_permission_dialog);
        recyclerView = findViewById(R.id.recycler_view);
    }

    private void initRecyclerView() {
        adapter = new SelectedImageAdapter(this, selectedImages, new GlideImageLoader(this));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(adapter);
    }

    private void initListeners() {
        // 选择图片
        btnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker(true, false, 9);
            }
        });

        // 选择视频
        btnSelectVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker(false, true, 3);
            }
        });

        // 图片视频混选
        btnSelectMixed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker(true, true, 9);
            }
        });

        // 单选模式
        btnSelectSingle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker(true, false, 1);
            }
        });

        // 拍照按钮开关
        switchCamera.setOnCheckedChangeListener((buttonView, isChecked) -> {
            showCameraButton = isChecked;
        });

        // 权限说明弹窗开关
        switchPermissionDialog.setOnCheckedChangeListener((buttonView, isChecked) -> {
            showPermissionDialog = isChecked;
        });
    }

    // 权限处理已移至相册库中，不再需要手动处理权限

    /**
     * 打开图片选择器
     */
    private void openImagePicker(boolean showImage, boolean showVideo, int maxCount) {
        // 创建图片加载器
        GlideImageLoader imageLoader = new GlideImageLoader(this);
        
        // 配置图片选择器
        ImagePicker.getInstance()
                .setTitle("选择图片")                    // 设置标题
                .showCamera(showCameraButton)           // 根据配置显示拍照按钮
                .showPermissionDialog(showPermissionDialog) // 根据配置显示权限说明弹窗
                .showImage(showImage)                   // 显示图片
                .showVideo(showVideo)                   // 显示视频
                .setSingleType(true)                    // 单一类型选择
                .setMaxCount(maxCount)                  // 最大选择数量
                .setImageLoader(imageLoader)            // 设置图片加载器
                .setImagePaths(getSelectedPaths())      // 设置已选择的图片路径
                .start(this, REQUEST_CODE_CHOOSE);      // 启动图片选择器
    }

    /**
     * 获取已选择的图片路径
     */
    private ArrayList<String> getSelectedPaths() {
        ArrayList<String> paths = new ArrayList<>();
        for (MediaFile mediaFile : selectedImages) {
            if (mediaFile.getPath() != null) {
                paths.add(mediaFile.getPath());
            }
        }
        return paths;
    }

    // 权限处理已移至相册库中，不再需要onRequestPermissionsResult

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                // 获取选择的图片路径列表
                ArrayList<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                if (imagePaths != null && !imagePaths.isEmpty()) {
                    handleSelectedImages(imagePaths);
                }
            }
        }
    }

    /**
     * 处理选择的图片
     */
    private void handleSelectedImages(ArrayList<String> imagePaths) {
        selectedImages.clear();
        
        for (String path : imagePaths) {
            MediaFile mediaFile = new MediaFile();
            mediaFile.setPath(path);
            
            // 根据文件扩展名判断类型
            if (path.toLowerCase().endsWith(".mp4") || 
                path.toLowerCase().endsWith(".avi") || 
                path.toLowerCase().endsWith(".mov")) {
                mediaFile.setMime("video/mp4");
            } else {
                mediaFile.setMime("image/jpeg");
            }
            
            selectedImages.add(mediaFile);
        }
        
        adapter.notifyDataSetChanged();
        
        Toast.makeText(this, "选择了 " + imagePaths.size() + " 个文件", Toast.LENGTH_SHORT).show();
    }

    // 权限处理已移至相册库中，不再需要显示权限说明对话框
}